using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UMC.Data;
using UMC.Web;
using UMC.Web.UI;

using UMC.WorkFlow.Entities;

namespace UMC.WorkFlow.Form
{
    public class FormUIActivity : WebActivity
    {
        bool IsCheck(Hashtable value, String sql)
        {
            var ls = new List<String>(Utility.GetFaramKeys(sql));
            ls.RemoveAll(g => String.Equals(g, "Keyword", StringComparison.CurrentCultureIgnoreCase));
            var em = value.GetEnumerator();
            while (em.MoveNext())
            {
                var k = em.Key.ToString();

                ls.RemoveAll(g => String.Equals(g, k, StringComparison.CurrentCultureIgnoreCase));
            }
            return ls.Count == 0;

        }
        bool IsCheckTip(Hashtable value, String sql, params string[] rKeys)
        {
            var ls = new List<String>(Utility.GetFaramKeys(sql));
            ls.RemoveAll(g => String.Equals(g, "Keyword", StringComparison.CurrentCultureIgnoreCase));
            var em = value.GetEnumerator();
            while (em.MoveNext())
            {
                var k = em.Key.ToString();

                ls.RemoveAll(g => String.Equals(g, k, StringComparison.CurrentCultureIgnoreCase));
            }
            foreach (var k in rKeys)
            {
                ls.RemoveAll(g => String.Equals(g, k, StringComparison.CurrentCultureIgnoreCase));
            }
            if (ls.Count > 0)
            {
                this.Prompt(String.Format("需要填写{0}字段", String.Join(",", ls.ToArray())));
            }
            return true;
        }

        void Process(WebRequest request, WebResponse response)
        {
            var form = request.SendValues ?? new UMC.Web.WebMeta();


            int limit = UMC.Data.Utility.IntParse(form["limit"] as string, 10);
            int start = UMC.Data.Utility.IntParse(form["start"] as string, 0);
            var Keyword = (form["Keyword"] as string ?? String.Empty);

            var ui = start == 0 ? UISection.Create(new UITitle(this.TaskForm.Caption)) : UISection.Create();
            if (start == 0)
            {
                ui.Title.Right(new UIEventText("新建").Click(new UIClick(request.Model, request.Command, "News")));
               
                var items = new List<WebMeta>
                {
                    new UMC.Web.WebMeta().Put("text", "待办").Put("search", new WebMeta().Put("Type", "Doing")),
                    new UMC.Web.WebMeta().Put("text", "发起").Put("search", new WebMeta().Put("Type", "Start")),
                    new UMC.Web.WebMeta().Put("text", "已办").Put("search", new WebMeta().Put("Type", "Done")),
                    new UMC.Web.WebMeta().Put("text", "知会").Put("search", new WebMeta().Put("Type", "Notify"))
                };
                ui.Add(UICell.Create("TabFixed", new UMC.Web.WebMeta().Put("items", items))); ;
            }

            switch (this.AsyncDialog("Type", "Doing"))
            {
                case "Doing":
                    this.Doing(ui, start, limit, Keyword);
                    break;
                case "Done":
                    this.Done(ui, start, limit, Keyword);
                    break;
                case "Start":
                    this.Start(ui, start, limit, Keyword);
                    break;
                case "Notify":
                    this.Notity(ui, start, limit, Keyword);
                    break;
            }
            ui.SendTo(this.Context, "WorkFlow.Progress");
            //response.Redirect(ui);
        }
        void Start(UISection ui, int start, int limit, String keywrok)
        {
            var userName = this.Context.Token.Username;

            var entity = HotCache.Search<TaskRequest>();

            if (String.IsNullOrEmpty(keywrok) == false)
            {
                entity.Or().Like(new TaskRequest
                {
                    Username = keywrok,
                    Subject = keywrok,
                    Description = keywrok
                });
            }
            var applys = entity.Query(new TaskRequest
            {
                Username = userName,
                TaskId = this.TaskForm.TaskId
            }, false, start, limit, out var _);
            var req = this.Context.Request;

            var reqArg = req.Arguments.GetDictionary();
            foreach (var apply in applys)
            {
                var data = new WebMeta();
                data["icon"] = "\uf007";
                data["ticon"] = "\uf073";
                data["time"] = String.Format("{0:yyyy.MM.dd HH:mm}", apply.ActiveTime);
                data["title"] = apply.Subject;

                var cell = new UICMS(new UIClick(req.Model, req.Command, new WebMeta(reqArg).Put("InstanceId", apply.InstanceId)), data);


                data["name"] = apply.ActiverAlias;

                var style = cell.Style.Name("tag");
                switch (apply.Status.Value)
                {
                    case TaskStatus.Completed:
                        style.BgColor(0x459df5);
                        cell.Tag("已完结");
                        break;
                    case TaskStatus.Locked:
                        style.BgColor(0x459df5);
                        cell.Tag("已完结");
                        break;
                    case TaskStatus.InReview:
                        style.BgColor(0x47a372);
                        cell.Tag("审批中");
                        break;
                    case TaskStatus.Prepare:
                        style.BgColor(0x47a372);
                        cell.Tag("准备中");
                        break;
                    case TaskStatus.Termination:
                        style.BgColor(0xBF3030);
                        cell.Tag("已终止");
                        break;
                }


                cell.Title("{title}");

                cell.Left("{icon} {name}");
                cell.Right("{ticon} {time}");
                cell.Style.Name("icon").Font("wdk").Size(12);
                cell.Style.Name("ticon").Font("wdk").Size(12);
                ui.Add(cell);
            }
            if (start == 0 && applys.Length == 0)
            {

                ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未有对应的发起").Put("icon", "\uEA05"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                   new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name 
            }

        }
        void Notity(UISection ui, int start, int limit, String keywrok)
        {
            var userName = this.Context.Token.Username;
            var entity = HotCache.Search<TaskMessage>();
            entity.Greater(new TaskMessage { Type = 1 });

               if (String.IsNullOrEmpty(keywrok) == false)
            {
                entity.Or().Like(new TaskMessage
                {
                    Username = keywrok,
                    Alias = keywrok,
                    Subject = keywrok,
                    Body = keywrok
                });
            }
            var applys =
            entity.Query(new TaskMessage
            {
                Username = userName,
                TaskId = this.TaskForm.TaskId

            }, true, start, limit, out var outIndex).OrderByDescending(r => r.CreationTime);

            var req = this.Context.Request;

            var reqArg = req.Arguments.GetDictionary();
            foreach (var apply in applys)
            {
                var data = new WebMeta();
                data["icon"] = "\uf007";
                data["ticon"] = "\uf073";
                data["time"] = String.Format("{0:yyyy.MM.dd HH:mm}", apply.CreationTime);
                data["title"] = apply.Subject;

                var cell = new UICMS(new UIClick(req.Model, req.Command, new WebMeta(reqArg).Put("InstanceId", apply.InstanceId)), data);


                data["name"] = apply.ProposerAlias ?? apply.Proposer;



                cell.Left("{icon} {name}");
                cell.Right("{ticon} {time}");
                cell.Style.Name("icon").Font("wdk").Size(12);
                cell.Style.Name("ticon").Font("wdk").Size(12);
                ui.Add(cell);
            }
            if (start == 0 && applys.Count() == 0)
            {

                ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未有对应的知会").Put("icon", "\uEA05"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                   new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name 
            }

        }
        void Done(UISection ui, int start, int limit, String keywrok)
        {
            var userName = this.Context.Token.Username;

            var entity = HotCache.Search<TaskHistory>();
            if (String.IsNullOrEmpty(keywrok) == false)
            {
                entity.Or().Like(new TaskHistory
                {
                    IdentityName = keywrok,
                    Proposer = keywrok,
                    ProposerAlias = keywrok,
                    Subject = keywrok
                });
            }

            var applys = entity.Query(new TaskHistory
            {

                IdentityName = userName,
                TaskId = this.TaskForm.TaskId
            }, false, start, limit, out var outIndex);
            var req = this.Context.Request;

            var reqArg = req.Arguments.GetDictionary();
            foreach (var apply in applys)
            {
                var data = new WebMeta();
                data["icon"] = "\uf007";
                data["ticon"] = "\uf073";
                data["time"] = String.Format("{0:yyyy.MM.dd HH:mm}", apply.RevertTime);
                data["title"] = apply.Subject;
                var cell = new UICMS(new UIClick(req.Model, req.Command, new WebMeta(reqArg).Put("InstanceId", apply.InstanceId)), data);
               
                data["name"] = apply.ProposerAlias ?? apply.Proposer;
                var style = cell.Style.Name("tag");
                switch (apply.Status.Value)
                {
                    case TaskStatus.Completed:
                        style.BgColor(0x459df5);
                        cell.Tag("已完结");
                        break;
                    case TaskStatus.Locked:
                        style.BgColor(0x459df5);
                        cell.Tag("已完结");
                        break;
                    case TaskStatus.InReview:
                        style.BgColor(0x47a372);
                        cell.Tag("审批中");
                        break;
                    case TaskStatus.Prepare:
                        style.BgColor(0x47a372);
                        cell.Tag("准备中");
                        break;
                    case TaskStatus.Termination:
                        style.BgColor(0xBF3030);
                        cell.Tag("已终止");
                        break;
                }


                cell.Title("{title}");
                cell.Left("{icon} {name}");
                cell.Right("{ticon} {time}");
                cell.Style.Name("icon").Font("wdk").Size(12);
                cell.Style.Name("ticon").Font("wdk").Size(12);
                ui.Add(cell);
            }
            if (start == 0 && applys.Length == 0)
            {

                ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未有对应的已办").Put("icon", "\uEA05"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                   new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name 
            }

        }
        void Doing(UISection ui, int start, int limit, String keywrok)
        {
            var userName = this.Context.Token.Username;
            var entity = HotCache.Search<TaskApproving>();
            if (String.IsNullOrEmpty(keywrok) == false)
            {
                entity.Or().Like(new TaskApproving
                {
                    Username = keywrok,
                    Alias = keywrok,
                    ProposerAlias = keywrok,
                    Proposer = keywrok,
                    Subject = keywrok,
                    Sender = keywrok,
                    SenderAlias = keywrok
                });
            }
            //var usernames = new List<String>();
            var applys = new List<TaskApproving>();
            entity.Query(new TaskApproving
            {
                Username = userName,
                TaskId = this.TaskForm.TaskId
            }, false, start, limit, out var _);
            var req = this.Context.Request;
            var reqArg = req.Arguments.GetDictionary();
            foreach (var apply in applys)
            {
                var data = new WebMeta();
                data["icon"] = "\uf007";
                data["ticon"] = "\uf073";
                data["time"] = String.Format("{0:yyyy.MM.dd HH:mm}", apply.ActiveTime);
                data["title"] = apply.Subject;

                var cell = new UICMS(new UIClick(req.Model, req.Command, new WebMeta(reqArg).Put("InstanceId", apply.InstanceId)), data);

                data["name"] = apply.ProposerAlias;



                cell.Left("{icon} {name}");
                cell.Right("{ticon} {time}");
                cell.Style.Name("icon").Font("wdk").Size(12);
                cell.Style.Name("ticon").Font("wdk").Size(12);
                ui.Add(cell);
            }
            if (start == 0 && applys.Count == 0)
            {

                ui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "未有对应的待办").Put("icon", "\uEA05"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                   new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name 
            }

        }
        TaskForm TaskForm;

        public FormUIActivity(TaskForm form)
        {
            this.TaskForm = form;
        }
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {

            var taskForm = this.TaskForm;
            var FormId = taskForm.TaskId.Value;
            var InstanceId = UMC.Data.Utility.UInt64Parse(this.AsyncDialog("InstanceId", g =>
            {
                Process(request, response);

                return this.DialogValue("none");
            })) ?? Utility.NewId();
            request.Arguments["InstanceId"] = InstanceId.ToString();
            var User = this.Context.Token;

            var task = UMC.WorkFlow.TaskRuntime.GetInstance(InstanceId);


            var cmds = task == null ? FormManager.GetCommands(this.TaskForm.TaskId.Value, new Identity(this.Context.Token))
                : FormManager.GetCommands(task, new Identity(this.Context.Token));
            var data = new List<TaskData>(DataFactory.Instance().TaskData(InstanceId));
            var checkData = new List<TaskCheckContorl>();
            var DefaultEdit = false;
            foreach (var m in cmds)
            {
                switch (m.Command)
                {
                    case CommandType.Save:
                    case CommandType.Submit:
                        DefaultEdit = true;
                        break;
                }
            }
            var controls = new List<TaskFormControl>(HotCache.Find(new TaskFormControl
            {
                TaskId = taskForm.TaskId
            }));
            var ShapeId = "Default";
            if (cmds.Length > 0)
            {
                ShapeId = cmds[0].ShapeId;

                if (controls.Count > 0)
                {
                    var ids = new List<ulong>();
                    foreach (var f in controls)
                    {
                        ids.Add(f.ItemId.Value);
                    }
                    //ids.to
                    var searcher = HotCache.Search<TaskCheckContorl>();
                    checkData.AddRange(searcher.In(new TaskCheckContorl { ShapeId = "Default" }, ShapeId)
                      .And().In(new TaskCheckContorl { ItemId = ids[0] }, ids).Query(new TaskCheckContorl(), false, 0, 10000, out var _));
                }

            }

            var InstanceData = new Hashtable();
            UMC.Data.Utility.Each(data.FindAll(td => td.DataIndex == -1), dr =>
            {
                InstanceData[dr.DataName] = dr.DataValue;
            });
            InstanceData["InstanceId"] = InstanceId;
            InstanceData["TaskId"] = taskForm.TaskId;


            var ItemId = Utility.UInt64Parse(this.AsyncDialog("Item", g =>
            {

                var argsValue = request.Arguments.GetDictionary();

                var ui = UISection.Create(new UITitle(taskForm.Caption));

                ui.UIFootBar = new UIFootBar();
                if (cmds.Length > 0)
                {
                    var args = new WebMeta();
                    args.Put("Task", taskForm.TaskId).Put("InstanceId", InstanceId);//.Put("Command",)
                    int count = 0;
                    foreach (var c in cmds)
                    {
                        var eventCmd = new UIEventText(c.Text).Click(new UIClick("WorkFlow", "Command", new WebMeta(args.GetDictionary()).Put("Command", c.Id)));
                        count++;
                        if (count % 2 == 0)
                        {
                            eventCmd.Style(new UIStyle().BgColor());
                        }
                        ui.UIFootBar.AddText(eventCmd);

                    }
                    ui.UIFootBar.IsFixed = true;
                }
                if (task != null)
                {
                    ui.AddCell('\uf007', "发起人", String.Format("{1}({0})", Utility.GetDate(task.StartTime), task.Identity.Alias), new UIClick("Account", "Staff", task.Identity.Username));

                    var anNO = data.Find(d => d.DataName == "ApplyNO");
                    if (anNO != null)
                    {

                        ui.AddCell('\uf162', "流程编号", anNO.DataValue);
                    }
                    else
                    {
                        ui.AddCell('\uf162', "流程编号", "未有");
                    }
                    var status = "准备中";
                    switch (task.Status)
                    {
                        case TaskStatus.Completed:
                            status = "已完结";
                            break;
                        case TaskStatus.Locked:
                            status = "被锁定";
                            break;
                        case TaskStatus.InReview:
                            status = "审阅中";
                            break;
                        case TaskStatus.Prepare:
                            status = "准备中";
                            break;
                        case TaskStatus.Termination:
                            status = "已终止";
                            break;
                    }
                    ui.AddCell('\uf0e8', "流程跟踪", status, new UIClick("WorkFlow", "Flow", task.InstanceId.ToString()));
                }
                else
                {
                    ui.AddCell('\uf007', "发起人", User.Alias, new UIClick("Account", "Staff", User.Username));
                    var anNO = data.Find(d => d.DataName == "ApplyNO");
                    if (anNO != null)
                    {
                        ui.AddCell('\uf162', "流程编号", anNO.DataValue);
                    }
                    else
                    {
                        ui.AddCell('\uf162', "流程编号", "自动");
                    }
                    ui.AddCell('\uf0e8', "流程跟踪", "未提交", new UIClick("WorkFlow", "Flow", this.TaskForm.TaskId.ToString()));

                }



                var ucl = ui.NewSection();
                foreach (var cl in controls)
                {
                    if ((cl.ForId ?? 0) != 0)
                    {
                        continue;
                    }
                    var isEdit = DefaultEdit;
                    var isInsert = isEdit;
                    var checks = checkData.FindAll(c => c.ItemId == cl.ItemId);
                    switch (checks.Count)
                    {
                        case 0:
                            break;
                        case 1:
                            switch (checks[0].ContorlMode)
                            {
                                case UIContorlMode.Insert:
                                    isInsert = true;
                                    isEdit = true;
                                    break;
                                case UIContorlMode.Edit:
                                    isInsert = false;
                                    isEdit = true;
                                    break;
                                case UIContorlMode.Hidden:
                                    continue;
                                case UIContorlMode.Readonly:
                                    isInsert = false;
                                    isEdit = false;
                                    break;
                                case UIContorlMode.Normal:
                                    break;
                            }
                            break;
                        case 2:
                            switch ((checks.Find(c => c.ShapeId == ShapeId) ?? checks[0]).ContorlMode)
                            {
                                case UIContorlMode.Insert:
                                    isInsert = true;
                                    isEdit = true;
                                    break;
                                case UIContorlMode.Edit:
                                    isEdit = true;
                                    break;
                                case UIContorlMode.Hidden:
                                    continue;
                                case UIContorlMode.Readonly:
                                    isEdit = false;
                                    break;
                                case UIContorlMode.Normal:
                                    break;
                            }
                            break;
                    }

                    //if (isEdit)
                    //{
                        if (String.IsNullOrEmpty(cl.ShowSQL) == false && IsCheck(InstanceData, cl.ShowSQL))
                        {
                            var dic = String.Format("{0}", Database.Instance(taskForm.ProviderKey)
                                .Sqler(false).ExecuteScalar(cl.ShowSQL, InstanceData));

                            if (Utility.IntParse(dic, 0) <= 0)
                            {
                                continue;
                            }

                        }

                    //}
                    if (cl.Type != ControlType.List)
                    {
                        if (String.IsNullOrEmpty(cl.Tip) == false)
                        {
                            ucl = ui.NewSection();
                            ucl.Header.Put("text", cl.Tip);
                        }
                    }
                    switch (cl.Type ?? ControlType.Text)
                    {
                        case ControlType.List:

                            ucl = ui.NewSection();
                            if (isInsert)
                            {
                                var UIfooter = new UIButton();
                                UIfooter.Title(cl.Caption);
                                UIfooter.Style.Name("min-width", 30);
                                UIfooter.Button(new UIEventText("增加").Style(new UIStyle().Color(0x3F51B5).Name("border", "none")).Click(new UMC.Web.UIClick(request.Model, request.Command, new WebMeta(argsValue).Put(g, cl.ItemId))));
                                ucl.Add(UIfooter);
                            }
                            else
                            {
                                ucl.Header.Put("text", cl.Caption);
                            }
                            var tls = controls.FindAll(ck => ck.ForId == cl.ItemId).OrderBy(r => r.Seq ?? 0).ToList();
                            var tlsData = data.FindAll(gk => String.Equals(gk.DataName, cl.Code, StringComparison.CurrentCultureIgnoreCase));
                            foreach (var titem in tlsData)
                            {
                                var value = UMC.Data.JSON.Deserialize<Hashtable>(titem.DataText) ?? new Hashtable();
                                value[cl.ValueKey] = titem.DataValue;
                                switch (tls.Count())
                                {
                                    case 1:
                                        {
                                           if (isEdit)
                                            {
                                                var cell = UICell.UI((value[tls[0].Code + "_Text"] ?? value[tls[0].Code]) as string, new UIClick(request, g, cl.ItemId.ToString(), "Index", titem.DataIndex.ToString()));

                                                ucl.Delete(cell, new UIEventText().Click(new UMC.Web.UIClick(request, g, cl.ItemId.ToString(), "Index", "+" + titem.DataIndex)));
                                            }
                                            else
                                            {
                                                ucl.AddCell((value[tls[0].Code + "_Text"] ?? value[tls[0].Code]) as string,"");
                                            }
                                        }
                                        break;
                                    case 2:
                                        {
                                            if (isEdit)
                                            {
                                                var cell = UICell.UI((value[tls[0].Code + "_Text"] ?? value[tls[0].Code]) as string, (value[tls[1].Code + "_Text"] ?? value[tls[1].Code]) as string, new UIClick(request, g, cl.ItemId.ToString(), "Index", titem.DataIndex.ToString()));

                                                ucl.Delete(cell, new UIEventText().Click(new UMC.Web.UIClick(request, g, cl.ItemId.ToString(), "Index", "+" + titem.DataIndex)));
                                            }
                                            else
                                            {
                                                ucl.AddCell((value[tls[0].Code + "_Text"] ?? value[tls[0].Code]) as string, (value[tls[1].Code + "_Text"] ?? value[tls[1].Code]) as string);
                                            }
                                        }
                                        break;
                                    case 0:
                                        break;
                                    default: {
                                            var cell = new UITextNameValue((value[tls[0].Code + "_Text"] ?? value[tls[0].Code]) as string, (value[tls[1].Code + "_Text"] ?? value[tls[1].Code]) as string, (value[tls[2].Code + "_Text"] ?? value[tls[2].Code]) as string);
                                            if (isEdit || tls.Count() > 3)
                                            {
                                                cell.Click(new UIClick(request, g, cl.ItemId.ToString(), "Index", titem.DataIndex.ToString()));
                                            }
                                            if (isEdit)
                                            {
                                               
                                                ucl.Delete(cell, new UIEventText().Click(new UMC.Web.UIClick(request, g, cl.ItemId.ToString(), "Index", "+" + titem.DataIndex)));
                                            }
                                            else
                                            {
                                                ucl.Add(cell);
                                            }

                                        }
                                        break;
                                }
                            }
                            if (tlsData.Count == 0)
                            {
                                var desc = new UMC.Web.UI.UIDesc(new UMC.Web.WebMeta().Put("desc", cl.PlaceHolder ?? cl.Caption).Put("icon", "\uF022"));
                                desc.Desc("{icon}\n{desc}");

                                desc.Style.Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60));

                                ucl.Add(desc);
                            }
                            ucl = ui.NewSection();
                            break;
                        case ControlType.Readonly:
                            {
                                var tlData = data.Find(gk => String.Equals(gk.DataName, cl.Code, StringComparison.CurrentCultureIgnoreCase));
                                if (tlData != null)
                                {
                                    var Text = tlData.DataText ?? tlData.DataValue;

                                    this.Detail(ucl, cl, Text, tlData.DataValue);
                                }
                                else
                                {
                                    ucl.AddCell(cl.Caption, cl.PlaceHolder);
                                }
                            }
                            break;
                        default:
                            {
                                var editClick = new UMC.Web.UIClick(request.Model, request.Command, new WebMeta(argsValue).Put(g, cl.ItemId));

                                var tlData = data.Find(gk => String.Equals(gk.DataName, cl.Code, StringComparison.CurrentCultureIgnoreCase));
                                if (tlData != null)
                                {
                                    var Text = tlData.DataText ?? tlData.DataValue;
                                    if (isEdit)
                                    {
                                        ucl.AddCell(cl.Caption, Text, editClick);

                                    }
                                    else
                                    {
                                        this.Detail(ucl, cl, Text, tlData.DataValue);
                                    }
                                }
                                else if (isEdit)
                                {
                                    ucl.AddCell(cl.Caption, cl.PlaceHolder
                                               , new UMC.Web.UIClick(request.Model, request.Command, new WebMeta(argsValue).Put(g, cl.ItemId)));
                                }
                                else
                                {
                                    ucl.AddCell(cl.Caption, cl.PlaceHolder);

                                }
                            }
                            break;
                    }

                }

                if (controls.Count == 0)
                {

                    ucl.Add("Desc", new UMC.Web.WebMeta().Put("desc", "空表单组件流程").Put("icon", "\uEA05")
                    , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),   new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));//.Name 
                }
                var log = HotCache.Find(new TaskLog { InstanceId = InstanceId }, true, 0, 1, out var _).FirstOrDefault();
                if (log != null)
                {
                    var se = ui.NewSection();
                    var dr = log;
                    var Str = "保存";
                    switch (dr.CommandType)
                    {
                        case CommandType.Apostille:
                            Str = "加签";
                            break;
                        case CommandType.Approval:
                            Str = "通过";
                            break;
                        case CommandType.Lock:
                            Str = "锁定";
                            break;
                        case CommandType.Reject:
                            Str = "驳回";
                            break;
                        case CommandType.Submit:
                            Str = "申请";
                            break;
                        case CommandType.Terminate:
                            Str = "终止";
                            break;
                    }

                    var cell = UICell.Create("Cell", new WebMeta().Put("value", "查看更多").Put("cmd", Str).Put("name", dr.Alias).Put("Icon", '\uf11e').Put("click", new UIClick("WorkFlow", "Log", dr.InstanceId.ToString())));
                    cell.Format("text", "由{name}提交{cmd}");
                    cell.Style.Name("cmd").Color(0x99232c); ;
                    cell.Style.Name("name").Color(0x999);
                    se.Add(cell);
                }
                ui.SendTo(this.Context, "WorkFlow.UI", "WorkFlow.Progress");


                return this.DialogValue("none");
            })).Value;

            var control = HotCache.Get(new TaskFormControl { ItemId = ItemId });
            var valueData = data.Find(g => g.DataName == control.Code) ?? new TaskData();
            switch (control.Type)
            {
                case ControlType.List:
                    var strIndex = this.AsyncDialog("Index", "-1");
                    var index = UMC.Data.Utility.IntParse(strIndex, 0);
                    if (strIndex.StartsWith("+"))
                    {

                        DataFactory.Instance().Delete(new TaskData
                        {
                            InstanceId = InstanceId,
                            DataIndex = index,
                            DataName = control.Code
                        });
                        this.Context.Send("WorkFlow.UI", true);
                    }

                    var va = data.Find(g => g.DataName == control.Code && g.DataIndex == index) ?? new TaskData();
                    if (String.IsNullOrEmpty(control.ValueKey))
                    {
                        this.Prompt("错误", String.Format("“{0}”列表组件未设置ValueKey", control.Code));
                    }

                    var value = UMC.Data.JSON.Deserialize<Hashtable>(va.DataText) ?? new Hashtable();
                    value[control.ValueKey] = va.DataValue;

                    var Values = this.AsyncDialog("Valuse", k =>
                    {
                        var frm = new UMC.Web.UIFormDialog() { Title = control.Caption };
                        var IsEdit = false;

                        Utility.Each(DataFactory.Instance().TaskFormControl(FormId, ItemId), dr =>
                         {
                             var checks = checkData.FindAll(c => c.ItemId == dr.ItemId);
                             switch ((checks.Find(c => c.ShapeId == ShapeId) ?? new TaskCheckContorl { ContorlMode = DefaultEdit? UIContorlMode.Edit: UIContorlMode.Readonly }).ContorlMode)
                             {
                                 case UIContorlMode.Insert:
                                 case UIContorlMode.Edit:
                                     IsEdit = true;
                                     break;
                                 case UIContorlMode.Hidden:
                                     return;
                                 case UIContorlMode.Readonly:
                                     dr.Type = ControlType.Readonly;
                                     break;
                                 case UIContorlMode.Normal:
                                     if (DefaultEdit)
                                     {
                                         dr.Type = ControlType.Readonly;
                                     }
                                     else
                                     {
                                         IsEdit = true;
                                     }
                                     break;
                             }
                             String itemValue = (value[dr.Code] as String) ?? String.Empty;
                             switch (dr.Type)
                             {
                                 case ControlType.Date:
                                     DateTime? valueDate = null;
                                     if (String.IsNullOrEmpty(itemValue) == false)
                                     {
                                         try
                                         {
                                             valueDate = Convert.ToDateTime(itemValue);
                                         }
                                         catch
                                         {

                                         }
                                     }
                                     frm.AddDate(dr.Caption, dr.Code, valueDate).PlaceHolder(dr.PlaceHolder);
                                     break;
                                 case ControlType.Number:
                                     frm.AddNumber(dr.Caption, dr.Code, itemValue).PlaceHolder(dr.PlaceHolder);
                                     break;
                                 default:
                                 case ControlType.Readonly:
                                     frm.Add(UICell.UI(dr.Caption, (value[String.Format("{0}_Text", dr.Code)] ?? itemValue) as string));
                                    
                                     break;
                                 case ControlType.Scaning:
                                     frm.AddScan(dr.Caption, dr.Code, itemValue).PlaceHolder(dr.PlaceHolder);
                                     break;
                                 case ControlType.Select:
                                     frm.AddOption(dr.Caption, dr.Code, itemValue, (value[String.Format("{0}_Text", dr.Code)] ?? itemValue) as string)
                                 .Command(request.Model, request.Command, new WebMeta(request.Arguments.GetDictionary()).Put("Item", dr.ItemId))
                                 .PlaceHolder(dr.PlaceHolder);
                                     break;
                                 case ControlType.Text:
                                     frm.AddText(dr.Caption, dr.Code, itemValue).PlaceHolder(dr.PlaceHolder);
                                     break;
                                 case ControlType.Areatext:
                                     frm.AddTextarea(dr.Caption, dr.Code, itemValue).PlaceHolder(dr.PlaceHolder);
                                     break;
                                 case ControlType.Attachment:
                                     frm.AddFile(dr.Caption, dr.Code, itemValue).Put("Accept", "*/*"); ;
                                     break;
                                 case ControlType.Icon:
                                 case ControlType.Image:
                                     frm.AddFile(dr.Caption, dr.Code, itemValue);
                                     break;
                             }
                         });
                        if (IsEdit)
                        {

                            frm.Submit("确认", "WorkFlow.UI");
                        }
                        else
                        {

                            frm.Submit("关闭");//, "WorkFlow.UI");
                        }
                        return frm;
                    });
                    var vs = Values.GetDictionary().GetEnumerator();
                    while (vs.MoveNext())
                    {
                        value[vs.Key] = vs.Value;
                    }

                    if (String.IsNullOrEmpty(control.CheckSQL) == false&&String.IsNullOrEmpty(taskForm.ProviderKey)==false)
                    {

                        var dic = Database.Instance(taskForm.ProviderKey).Sqler(false).ExecuteScalar(control.CheckSQL, value);
                        if (dic is string)
                        {
                            this.Prompt(dic as string);
                        }
                    }
                    if (String.IsNullOrEmpty(control.ValueSQL) == false && String.IsNullOrEmpty(taskForm.ProviderKey) == false)
                    {
                        var dic = Database.Instance(taskForm.ProviderKey).Sqler(false).ExecuteSingle(control.ValueSQL, value).GetEnumerator();
                        while (dic.MoveNext())
                        {
                            value[dic.Key] = dic.Value;
                        }
                    }

                    va.DataValue = value[control.ValueKey] as string;
                    va.DataText = JSON.Serialize(value);
                    if (index == -1)
                    {

                        var max = DataFactory.Instance().TaskData(InstanceId, control.Code).MaxBy(t => t.DataIndex ?? 0) ?? new TaskData();// .Max(new TaskData { DataIndex = 0 });
                        va.DataIndex = (max.DataIndex ?? 0) + 1;
                        va.DataName = control.Code;
                        va.InstanceId = InstanceId;
                        DataFactory.Instance().Put(va);
                    }
                    else
                    {
                        va.DataIndex = index;
                        va.DataName = control.Code;
                        va.InstanceId = InstanceId;
                        DataFactory.Instance().Put(va);
                    }
                    break;

                default:
                    if (String.IsNullOrEmpty(control.CheckSQL) == false)
                    {
                        this.IsCheckTip(InstanceData, control.CheckSQL, "InstanceId", "DataValue", "DataName");
                    }
                    if (String.IsNullOrEmpty(control.ValueSQL) == false)
                    {
                        this.IsCheckTip(InstanceData, control.ValueSQL, "InstanceId", "DataValue", "DataName");
                    }

                    var Value = this.AsyncDialog("Value", k =>
                    {
                        switch (control.Type)
                        {
                            case ControlType.Icon:
                                {
                                    var file = UMC.Web.UIDialog.Create("File");
                                    file.Title = control.Caption;
                                    return file;
                                }
                            case ControlType.Image:
                                {
                                    var file = UMC.Web.UIDialog.Create("File");
                                    file.Title = control.Caption;
                                    return file;
                                }
                            case ControlType.Attachment:
                                {
                                    var file = UMC.Web.UIDialog.Create("File");
                                    file.Title = control.Caption;
                                    file.Config.Put("Accept", "*/*");
                                    return file;
                                }
                            case ControlType.Scaning:
                                return new UMC.Web.UIScanDialog()
                                {
                                    DefaultValue = valueData.DataValue,
                                    Title = control.Caption
                                };
                            case ControlType.Date:
                                return new UMC.Web.UIDateDialog()
                                {
                                    DefaultValue = valueData.DataValue,
                                    Title = control.Caption
                                };
                            case ControlType.Number:
                                return new UMC.Web.UINumberDialog()
                                {
                                    DefaultValue = valueData.DataValue,
                                    Title = control.Caption
                                };
                            default:
                            case ControlType.Text:
                                return new UMC.Web.UITextDialog()
                                {
                                    DefaultValue = valueData.DataValue,
                                    Title = control.Caption
                                };
                            case ControlType.Select:

                                if (String.IsNullOrEmpty(control.SelectCommand))
                                {
                                    this.Prompt("未配置选择方式");
                                }
                                var cmdindex = control.SelectCommand.IndexOf('.');

                                this.AsyncDialog(k, control.SelectCommand.Substring(0, cmdindex), control.SelectCommand.Substring(cmdindex + 1));
                                return this.DialogValue("none");
                        }
                    });
                    var spIndex = Value.IndexOf('|');
                    if (spIndex > -1)
                    {

                        valueData.DataValue = Value.Substring(0, spIndex);
                        valueData.DataText = Value.Substring(spIndex + 1);
                    }
                    else
                    {
                        valueData.DataValue = Value;
                        valueData.DataText = (request.SendValues ?? request.Arguments)["Value_Text"] ?? Value;
                    }
                    valueData.DataIndex = -1;
                    valueData.DataName = control.Code;
                    valueData.InstanceId = InstanceId;
                    if (control.ForId.HasValue && control.ForId.Value != 0)
                    {

                        this.Context.UIEvent(control.Code, new ListItem(valueData.DataText, valueData.DataValue)), true);
                    }
                    else
                    {
                        var hashtable = new Hashtable(InstanceData);
                        hashtable["InstanceId"] = InstanceId;
                        hashtable["DataValue"] = valueData.DataValue;
                        hashtable["DataName"] = control.Code;

                        if (String.IsNullOrEmpty(control.CheckSQL) == false)
                        {
                            this.IsCheckTip(hashtable, control.CheckSQL);
                            var dic = Database.Instance(taskForm.ProviderKey).Sqler(false).ExecuteScalar(control.CheckSQL, hashtable);
                            if (dic is string)
                            {
                                this.Prompt(dic as string);
                            }
                        }
                        if (String.IsNullOrEmpty(control.ValueSQL) == false)
                        {
                            var names = new List<String>();
                            this.IsCheckTip(hashtable, control.ValueSQL);
                            var tdata = new List<TaskData>();
                            tdata.Add(valueData);
                            names.Add(control.Code);
                            var dic = Database.Instance(taskForm.ProviderKey).Sqler(false).ExecuteSingle(control.ValueSQL, hashtable).GetEnumerator();
                            while (dic.MoveNext())
                            {
                                var key = dic.Key.ToString();
                                names.Add(key);
                                tdata.RemoveAll(g => g.DataName == key);
                                tdata.Add(new TaskData
                                {
                                    DataIndex = -1,
                                    DataName = key,// dic.Key.ToString(),
                                    DataValue = dic.Value.ToString(),
                                    DataText = dic.Value.ToString(),
                                    InstanceId = InstanceId
                                });
                            }
                            names.RemoveAll(n => tdata.Exists(t => t.DataName == n));
                            foreach (var n in names)
                            {
                                Utility.Each(DataFactory.Instance().TaskData(InstanceId, n), r => DataFactory.Instance().Delete(r));
                            }
                            foreach (var d in tdata)
                            {
                                DataFactory.Instance().Put(d);
                            }
                        }
                        else
                        {


                            DataFactory.Instance().Put(valueData);
                        }

                    }
                    break;
            }

            this.Context.Send("WorkFlow.UI", true);
        }
        void Detail(UISection ucl, TaskFormControl cl, String text, String value)
        {
            if (String.IsNullOrEmpty(cl.DetailCommand) == false)
            {
                var pIndex = cl.DetailCommand.IndexOf('.');
                if (pIndex > 0)
                {
                    if (String.IsNullOrEmpty(value))
                    {
                        ucl.AddCell(cl.Caption, text);
                    }
                    else
                    {

                        ucl.AddCell(cl.Caption, text, new UIClick(cl.DetailCommand.Substring(0, pIndex), cl.DetailCommand.Substring(pIndex + 1), value));
                    }
                }
                else
                {
                    ucl.AddCell(cl.Caption, text);
                }
            }
            else
            {
                ucl.AddCell(cl.Caption, text);
            }

        }

    }
}